package com.lemon.boot.service.impl;

import com.lemon.boot.common.base.BaseServiceImpl;
import com.lemon.boot.common.thread.pool.ExecutorThreadPoolGroup;
import com.lemon.boot.common.utils.JwtUtil;
import com.lemon.boot.dao.NoticeUserDAO;
import com.lemon.boot.dto.NoticeUserDTO;
import com.lemon.boot.po.NoticeUserPO;
import com.lemon.boot.service.IDeptUserService;
import com.lemon.boot.service.INoticeUserService;
import com.lemon.boot.common.socket.NoticeWebSocketService;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 公告用户中间表 业务实现类
 *
 * @author Lemon
 * @since 2024-02-29
 */
@Log4j2
@Service
public class NoticeUserServiceImpl extends BaseServiceImpl<NoticeUserDAO, NoticeUserPO, NoticeUserDTO> implements INoticeUserService {
    @Resource
    @Lazy
    private NoticeWebSocketService noticeWebSocketService;
    @Resource
    private IDeptUserService iDeptUserService;

    @Override
    public void readByNoticeId(Long noticeId) {
        //1.当前用户
        final Long userId = JwtUtil.getCurrentUser().getUserId();

        //2.缓存线程池
        final ExecutorService executorService = ExecutorThreadPoolGroup.noticeExecutorService;

        //3.异步执行
        executorService.submit(() -> {
            //3.1.标记已读
            this.update().set("is_read", 1).eq("user_id", userId).eq("notice_id", noticeId).update();

            //3.2.推送消息
            noticeWebSocketService.send(userId);
        });
    }

    @Override
    @Transactional
    public void addByDeptIdList(Long noticeId, List<Long> deptIdList) {
        //1.根据部门ID查询部门下的所有用户ID
        List<Long> userIdList = iDeptUserService.getUserIdByDeptIdList(deptIdList);
        if (!CollectionUtils.isEmpty(userIdList)) {
            List<NoticeUserPO> noticeUserList = userIdList.stream().distinct()
                    .map(item -> new NoticeUserPO().setUserId(item).setNoticeId(noticeId).setIsRead(0))
                    .collect(Collectors.toList());

            //2.批量添加消息
            this.saveBatch(noticeUserList, Integer.MAX_VALUE);

            //3.websocket推送消息
            noticeWebSocketService.send();
        }
    }
}